/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.qxp.simplerpc.server;

import com.qxp.simplerpc.codec.RpcDecoder;
import com.qxp.simplerpc.codec.RpcEncoder;
import com.qxp.simplerpc.connect.AbstractConnector;
import com.qxp.simplerpc.entity.InvokerMessage;
import com.qxp.simplerpc.utils.SimpleRpcProperties;
import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author qianxiaopeng
 */
@Component
public final class RpcServer extends AbstractConnector implements Runnable {
    // logger
    private static Logger logger = LoggerFactory.getLogger(RpcServer.class);
    @Autowired
    private RpcServerHandler rpcServerHandler;
    @Autowired
    private SimpleRpcProperties simpleRpcProperties;

    @Override
    public void run() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        this.doConnect(serverBootstrap);
    }
    @Override
    protected void doConnect(AbstractBootstrap abstractBootstrap) {
        SslContext sslCtx = getSsL();
        EventLoopGroup bossGroup = new NioEventLoopGroup(simpleRpcProperties.getBossThreadn());
        EventLoopGroup workerGroup = new NioEventLoopGroup(simpleRpcProperties.getWorkThreadn());
        ServerBootstrap serverBootstrap = (ServerBootstrap)abstractBootstrap;
        try {
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            // 管道
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc()));
                            }
                            p.addLast(
                                    // 序列化对象
                                    new RpcDecoder(InvokerMessage.class),
                                    new RpcEncoder(InvokerMessage.class),
                                    // 监视句柄
                                    rpcServerHandler);
                        }
                    })
                    .bind(simpleRpcProperties.getPort()).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    protected SslContext getSsL() {
        // Configure SSL.
        SslContext sslCtx = null;
        if (simpleRpcProperties.isSsl()) {
            SelfSignedCertificate ssc = null;
            try {
                ssc = new SelfSignedCertificate();
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
            } catch (Exception e) {
                logger.error("get ssc fail,caused by:\n",e);
            }
        }
        return sslCtx;
    }


}
